package com.common.web.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.springframework.aop.framework.AopInfrastructureBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class HttpServiceClient implements AopInfrastructureBean {

    @Autowired
    private RestTemplate restTemplate;
    
    public String restPost(String url,Object param) {
    	HttpHeaders headers = new HttpHeaders();
    	headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
    	String requestJson=JSON.toJSONString(param);
    	HttpEntity<String> requestEntity = new HttpEntity<>(requestJson, headers);
    	return restTemplate.postForObject(url, requestEntity, String.class);
    }
    
    
    public String restGet(String url,Map<String,Object> params) {
		if(url.contains("{")&&url.contains("}")) {
			return restTemplate.getForObject(url,  String.class, params);			
		}else {
			String requestUrl=buildUrl(url, params);
			return restTemplate.getForObject(requestUrl, String.class);
		}
    }
    
    
	private String buildUrl(String url, Map<String, Object> params) {
		StringBuilder buffer=new StringBuilder(url);
		if(!url.endsWith("?")) {
			buffer.append("?");
		}
		if(params!=null) {
			params.forEach((key,value)->{
				buffer.append(key).append("=").append(value).append("&");
			});
		}
		String reqestSql=buffer.toString();
		if(reqestSql.equals("&")) {
			reqestSql=reqestSql.substring(0, reqestSql.length()-1);
		}
		return reqestSql;
	}


	public ResponseEntity<String> httpPost(String url, String param) throws Exception {
		PrintWriter out = null;
		InputStream is = null;
		BufferedReader br = null;
		String result = "";
		HttpURLConnection conn = null;
		try {
			URL realUrl = new URL(url);
			conn = (HttpURLConnection) realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(20000);
			conn.setReadTimeout(300000);
			conn.setRequestProperty("Charset", "UTF-8");

			// 传输数据为json，如果为其他格式可以进行修改
			conn.setRequestProperty( "Content-Type", "application/json");
			conn.setRequestProperty( "Content-Encoding", "utf-8");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput( true);
			conn.setDoInput( true);
			conn.setUseCaches( false);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			is = conn.getInputStream();
			br = new BufferedReader( new InputStreamReader(is));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line=br.readLine())!= null) {
				sb.append(line);
			}
			result = sb.toString();
		} catch(IOException e){
			log.warn(e.getMessage());
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (br != null) {
					br.close();
				}
				if (conn!= null) {
					conn.disconnect();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return new ResponseEntity<>(result, HttpStatus.OK);
	}
}
